import React, {useEffect, useRef, useState} from 'react';
import type {ActionType, ProColumns, ProFormInstance} from '@ant-design/pro-components';
import {ProForm, ProTable} from '@ant-design/pro-components';
import {Modal, Button, Form, Select, message} from 'antd';
import {
  addRolePermissionUsingPost,
  deleteRolePermissionUsingPost,
  listPermissionUsingPost, listRoleExPermissionUsingPost
} from "@/services/easyapi/eRoleCenter";
import {from} from "stylis";

export type Props = {
  role: API.PageRoleVo;
  visible: boolean;
  onCancel: () => void;
};

const RoleEmpower: React.FC<Props> = (props) => {
  const {visible, onCancel, role} = props;
  const formRef = useRef<ProFormInstance<any>>();
  const [dataSource, setDataSource] = useState<API.PermissionVo[]>([]);
  const [isAddModalVisible, setAddModalVisible] = useState(false);
  const [form] = Form.useForm();
  const [options, setOptions] = useState<API.PermissionVo[]>([]);
  const actionRef = useRef<ActionType>();
  useEffect(() => {
    if (visible) {
      listPermissionUsingPost({
        id: role.id
      }).then((res) => {
        setDataSource(res.data || [])
      });
    }
  }, [visible]);

  const handleRevoke = async (roleId: number, permissionId: number) => {
    const res = await deleteRolePermissionUsingPost({
      roleId: roleId,
      permissionId: permissionId
    });
    if (res.code === 200) {
      message.success('操作成功')
    } else {
      message.error(res.msg);
    }
    actionRef.current?.reload()
  }


  const listAllPermission = async () => {
    const res = await listRoleExPermissionUsingPost({
      id: role.id,
    });
    if (res.code === 200) {
      setOptions(
        //@ts-ignore
        res.data.map((permission) => ({
          label: permission.display,
          value: permission.id
        }))
      )
    } else {
      message.error(res.msg);
    }
  }

  const handleAdd = async () => {
    const permission = await form.validateFields();
    ;
    const res = await addRolePermissionUsingPost({
      roleId: role.id,
      permissionId: permission.id,
    })
    if (res.code === 200) {
      message.success('操作成功')
    } else {
      message.error(res.msg);
    }
    setAddModalVisible(false)
    listPermissionByRoleId()
    form.resetFields()
  }

  const columns: ProColumns<API.PermissionVo>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      hideInTable: true,
      hideInForm: true,
    },
    {
      title: '权限',
      dataIndex: 'display',
      width: '30%',
    },
    {
      title: '操作',
      valueType: 'option',
      width: '20%',
      render: (_, record) => {
        return (
          <Button
            type="link"
            danger
            // @ts-ignore
            onClick={() => handleRevoke(role.id, record.id)}
          >
            取消授权
          </Button>
        );
      }
    },
  ];

  const listPermissionByRoleId = async () => {
    const res = await listPermissionUsingPost({
      id: role.id,
    });
    if (res.code === 200) {
      setDataSource(res.data || []);
    }
  }

  return (
    <>
      <Modal width="50%" visible={visible} footer={null} onCancel={onCancel}>
        <ProForm<{
          table: API.PermissionVo[];
        }>
          formRef={formRef}
          initialValues={{
            table: dataSource,
          }}
          validateTrigger="onBlur"
          submitter={false} // Disable the submit button and other controls
        >
          <ProTable<API.PermissionVo>
            rowKey="id"
            scroll={{
              x: 500,
            }}
            actionRef={actionRef}
            //@ts-ignore
            request={() => {
              listPermissionByRoleId();
            }}
            columns={columns}
            dataSource={dataSource}
            pagination={false}
            search={false}
            toolBarRender={() => [
              // eslint-disable-next-line react/jsx-key
              <Button
                type="primary"
                onClick={() => {
                  listAllPermission()
                  setAddModalVisible(true)
                }}
              >
                新增授权
              </Button>,
            ]}
          />
        </ProForm>
      </Modal>

      <Modal
        title="新增授权"
        visible={isAddModalVisible}
        onCancel={() => setAddModalVisible(false)}
        onOk={() => form.submit()}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleAdd}
        >
          <Form.Item
            name="id"
            label="角色"
            rules={[{required: true, message: '角色为必填项'}]}
          >
            <Select
              options={options}
              placeholder="请选择角色"
            />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default RoleEmpower;
